document.addEventListener('DOMContentLoaded', () => {
    const articleUrlInput = document.getElementById('articleUrl');
    const generateBtn = document.getElementById('generateBtn');
    const exportBtn = document.getElementById('exportBtn');
    const copyBtn = document.getElementById('copyBtn');
    const loadingElement = document.getElementById('loading');
    const errorElement = document.getElementById('error');
    const errorMessage = document.getElementById('errorMessage');
    const markdownContent = document.getElementById('markdown-content');

    let rawContent = ''; // 存储原始 markdown 内容

    // 配置 marked 选项
    marked.setOptions({
        breaks: true,  // 支持 GitHub 风格的换行
        gfm: true,     // 启用 GitHub 风格的 Markdown
        headerIds: true, // 为标题添加 id
        mangle: false,  // 不转义标题中的特殊字符
        headerPrefix: '', // 不添加标题前缀
        highlight: function(code, lang) {
            // 使用 highlight.js 进行代码高亮
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return hljs.highlight(code, { language: lang }).value;
                } catch (err) {}
            }
            return code;
        }
    });

    // 生成文章结构
    async function generateMindmap() {
        const url = articleUrlInput.value.trim();
        
        if (!url) {
            showError('请输入文章 URL');
            return;
        }

        try {
            // 显示加载状态
            showLoading(true);
            hideError();
            
            // 发送请求
            const response = await fetch('/api/generate-mindmap', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ url })
            });

            const data = await response.json();

            if (data.success && data.mindmap) {
                // 保存原始内容
                rawContent = data.mindmap;
                
                // 渲染 Markdown 内容
                const renderedContent = marked.parse(data.mindmap);
                markdownContent.innerHTML = renderedContent;
                
                // 启用按钮
                exportBtn.disabled = false;
                copyBtn.disabled = false;
                
                // 添加复制按钮到每个代码块
                addCopyButtonsToCodeBlocks();
                
                // 应用代码高亮
                markdownContent.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });
            } else {
                throw new Error(data.error || '生成失败，请重试');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            showLoading(false);
        }
    }

    // 导出 Markdown 文件
    function exportMarkdown() {
        if (!rawContent) return;

        const blob = new Blob([rawContent], { type: 'text/markdown' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'article_structure.md';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 复制全文内容
    async function copyContent() {
        if (!rawContent) return;

        try {
            await navigator.clipboard.writeText(rawContent);
            const originalText = copyBtn.textContent;
            copyBtn.textContent = '已复制！';
            copyBtn.disabled = true;
            
            setTimeout(() => {
                copyBtn.textContent = originalText;
                copyBtn.disabled = false;
            }, 2000);
        } catch (err) {
            showError('复制失败，请手动复制');
        }
    }

    // 为代码块添加复制按钮
    function addCopyButtonsToCodeBlocks() {
        const codeBlocks = markdownContent.querySelectorAll('pre code');
        codeBlocks.forEach(block => {
            const wrapper = document.createElement('div');
            wrapper.className = 'code-block-wrapper';
            
            const copyButton = document.createElement('button');
            copyButton.className = 'copy-button';
            copyButton.textContent = '复制';
            copyButton.onclick = async () => {
                try {
                    await navigator.clipboard.writeText(block.textContent);
                    copyButton.textContent = '已复制！';
                    copyButton.disabled = true;
                    
                    setTimeout(() => {
                        copyButton.textContent = '复制';
                        copyButton.disabled = false;
                    }, 2000);
                } catch (err) {
                    console.error('复制失败:', err);
                }
            };
            
            block.parentNode.insertBefore(wrapper, block);
            wrapper.appendChild(block);
            wrapper.appendChild(copyButton);
        });
    }

    // 显示/隐藏加载状态
    function showLoading(show) {
        loadingElement.style.display = show ? 'flex' : 'none';
        generateBtn.disabled = show;
        if (show) {
            exportBtn.disabled = true;
            copyBtn.disabled = true;
        }
    }

    // 显示错误信息
    function showError(message) {
        errorElement.style.display = 'block';
        errorMessage.textContent = message;
    }

    // 隐藏错误信息
    function hideError() {
        errorElement.style.display = 'none';
    }

    // 事件监听
    generateBtn.addEventListener('click', generateMindmap);
    exportBtn.addEventListener('click', exportMarkdown);
    copyBtn.addEventListener('click', copyContent);
    
    // 输入框回车触发生成
    articleUrlInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            generateMindmap();
        }
    });
}); 